<template>
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="1100"
      draggable
      @close="closeDialog"
    >
      <el-row>
        <el-col
          class="search-container"
          :span="7"
          :offset="1"
          style="height: 420px"
        >
          <el-form :model="formData" :inline="true" label-width="100px">
            <el-form-item label="物料号">
              <el-input
                v-model="formData.materialCode"
                placeholder="请选择物料号"
                clearable
                disabled
              >
                <!-- <template #append>
                <el-button type="success" plain @click="showWorkOrderSelect"
                  >选择</el-button
                >
              </template> -->
              </el-input>
            </el-form-item>
            <el-form-item label="供应商">
              <el-input
                v-model="formData.partnerCode"
                placeholder="请选择供应商"
                clearable
                disabled
              >
                <!-- <template #append>
                <el-button type="success" plain @click="showWorkOrderSelect2"
                  >选择</el-button
                >
              </template> -->
              </el-input>
            </el-form-item>
            <el-form-item label="批次">
              <el-input
                v-model="formData.batch"
                placeholder="请输入批次(6位)"
                clearable
                disabled
              />
            </el-form-item>
            <el-form-item label="流水号1">
              <el-input
                v-model="formData.serial1"
                placeholder="请输入流水号"
                clearable
                disabled
              />
            </el-form-item>
            <el-form-item label="流水号2">
              <el-input
                v-model="formData.serial2"
                placeholder="流水号2为空"
                clearable
                disabled
              />
            </el-form-item>
            <el-form-item label="流水号3">
              <el-input
                v-model="formData.serial3"
                placeholder="流水号3为空"
                clearable
                disabled
              />
            </el-form-item>
            <el-form-item style="width: 70%; margin-left: 10%">
              <el-button type="primary" @click="getBarCode" style="width: 100%"
                >预览</el-button
              >
            </el-form-item>

            <!-- <el-form-item label="打印机">
            <el-select
              v-model="formData.printer"
              clearable
              placeholder="请选打印机"
              style="width: 250px"
            >
              <el-option
                v-for="item in printers"
                :key="item.printerName"
                :label="item.printerName"
                :value="item.printerName"
              />
            </el-select>
          </el-form-item> -->

            <el-form-item style="width: 70%; margin-left: 10%">
              <el-button
                type="primary"
                @click="printFun"
                style="width: 100%"
                :disabled="isPrint"
                >打印</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
        <el-col
          class="search-container"
          :span="15"
          :offset="1"
          style="height: 600px; padding-top: 60px"
          border="1"
          id="printId"
        >
          <table align="center" width="80%" cellspacing="0">
            <tr>
              <td>物料号</td>
              <td>{{ formData.materialCode }}</td>
              <td>物料描述</td>
              <td>{{ formData.materialName }}</td>
            </tr>
            <tr>
              <td>供应商代码</td>
              <td>{{ formData.partnerCode }}</td>
              <td>供应商</td>
              <td>{{ formData.partnerName }}</td>
            </tr>
            <tr>
              <td>批次</td>
              <td>{{ formData.batch }}</td>
              <td colspan="2" rowspan="4" id="showQrP">
                <canvas id="showQr"></canvas>
              </td>
            </tr>
            <tr>
              <td>流水号1</td>
              <td>{{ formData.serial1 }}</td>
            </tr>
            <tr>
              <td>流水号2</td>
              <td>{{ formData.serial2 }}</td>
            </tr>
            <tr>
              <td>流水号3</td>
              <td>{{ formData.serial3 }}</td>
            </tr>
            <tr style="height: 65px">
              <td colspan="4" style="height: 45px">
                {{ pCode }}
              </td>
            </tr>
          </table>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import QRCode from "qrcode";
import defaultSettings from "@/settings";
import { useRoute } from "vue-router";
import { getLodop } from "@/utils/LodopFuncs";
const dictionaryStore = useDictStoreHook();
let isPrint = ref(true);

defineOptions({
  name: "LABELPRINTING",
  inheritAttrs: false,
});

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

const emit = defineEmits(["reset-table", "change-visible"]);
/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  //resetForm();
}

// 初始化搜索参数数据
let formData = reactive({
  partnerId: "",
  partnerCode: "",
  partnerName: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  poSa: "",
  poSaItem: "",
  batch: YYMMDD(),
  serial1: "000001",
  serial2: "",
  serial3: "",
  number: 1,
  printer: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    console.log("newVal:", newVal);
    if (newVal?.materialId) {
      const {
        partnerId,
        partnerCode,
        partnerName,
        materialId,
        materialCode,
        materialName,
        batch,
        serial1,
        serial2,
        serial3,
        number,
        printer,
      } = newVal;
      Object.assign(formData, {
        partnerId,
        partnerCode,
        partnerName,
        materialId,
        materialCode,
        materialName,
        batch,
        serial1,
        serial2,
        serial3,
        number,
        printer,
      });
    }
  }
);

let pCode = ref();

function YYMMDD() {
  var myDate = new Date();
  var month = myDate.getMonth() + 1;
  var Day = myDate.getDate();
  var today = "";
  if (month < 10) {
    if (Day < 10) {
      today =
        myDate.getFullYear().toString().slice(-2) + "0" + month + "0" + Day;
    } else {
      today = myDate.getFullYear().toString().slice(-2) + "0" + month + Day;
    }
  } else {
    if (Day < 10) {
      today = myDate.getFullYear().toString().slice(-2) + month + "0" + Day;
    } else {
      today = myDate.getFullYear().toString().slice(-2) + month + Day + "";
    }
  }
  return today;
}
// 获取打印数据
async function getBarCode() {
  if (!formData.batch || formData.batch.length != 6) {
    ElMessage.error("批次必须为6位");
    return;
  }
  if (!formData.serial1 || formData.serial1.length != 6) {
    ElMessage.error("流水号必须为6位");
    return;
  }
  pCode.value = `Mt${formData.materialCode}`;
  if (formData.partnerCode) {
    pCode.value += `-Pt${formData.partnerCode}`;
  }
  pCode.value += `-Sb${formData.batch}`;
  pCode.value += `-Na${formData.serial1}`;
  if (formData.serial2) {
    pCode.value += `-Nb${formData.serial2}`;
  }
  if (formData.serial3) {
    pCode.value += `-Nc${formData.serial3}`;
  }
  const datam = await request({
    url: `/wms/mdmmaterial/queryByCode`,
    method: "post",
    data: { materialCode: formData.materialCode },
  }).finally(() => {});
  if (datam.code == 200 && datam.data) {
    formData.materialName = datam.data.materialName;
  } else {
    ElMessage.error("物料号对应物料未维护");
  }
  const datap = await request({
    url: `/wms/mdmpartner/queryByCode`,
    method: "post",
    data: { partnerCode: formData.partnerCode },
  }).finally(() => {});
  if (datap.code == 200 && datap.data) {
    formData.partnerName = datap.data.partnerName;
  } else {
    ElMessage.error("供应商号对应供应商未维护");
  }
  if (datam.code == 200 && datap.code == 200 && datam.data && datap.data) {
    isPrint.value = false;
    QRCode.toCanvas(document.getElementById("showQr"), pCode.value, {
      width: 230, // 可以根据需要调整二维码的大小
      margin: 1, // 可以根据需要调整二维码的边距
    });
  }
}

// 打印模板全用div和span等原生html书写（确保打印格式不变）
// 样式全用行内style书写（确保样式生效）

const route = useRoute();
function printFun(pitem: RootObject) {
  let LODOP = getLodop();
  LODOP.SET_PRINTER_INDEX(formData.printer);
  LODOP.PRINT_INIT(`打印-${pCode.value}`);
  LODOP.SET_LICENSES(
    defaultSettings.printCompany,
    defaultSettings.printLicenses,
    "",
    ""
  );
  LODOP.SET_PRINT_STYLE("Bold", 1);
  LODOP.SET_PRINT_STYLE("FontSize", 9);
  LODOP.SET_PRINT_STYLE("Stretch");
  LODOP.SET_PRINT_STYLE("FontName", "cursive"); // 需要服务端机器安装同样字体，才能生效
  LODOP.SET_PRINT_PAGESIZE(1, 9500, 580, ""); // 设置纸张类型（方向、宽度、高度、纸张类型名称）
  LODOP.ADD_PRINT_LINE("14%", 0, "14%", "100%", 0, 1);
  LODOP.ADD_PRINT_LINE("30%", 0, "30%", "100%", 0, 1);
  LODOP.ADD_PRINT_LINE("48%", 0, "48%", "45%", 0, 1);
  LODOP.ADD_PRINT_LINE("63%", 0, "63%", "45%", 0, 1);
  LODOP.ADD_PRINT_LINE("78%", 0, "78%", "45%", 0, 1);
  LODOP.ADD_PRINT_LINE("92%", 0, "92%", "45%", 0, 1);
  LODOP.ADD_PRINT_LINE(0, "25%", "92%", "25%", 0, 1);
  LODOP.ADD_PRINT_LINE(0, "45%", "92%", "45%", 0, 1);
  LODOP.ADD_PRINT_LINE(0, "60%", "30%", "60%", 0, 1);
  LODOP.ADD_PRINT_TEXT("5%", "10%", "23%", "15%", "物料号"); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("5%", "27%", "25%", "15%", formData.materialCode); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("5%", "46%", "25%", "15%", "物料描述"); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("20%", "10%", "23%", "15%", "供应商码"); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("20%", "27%", "25%", "15%", formData.partnerCode); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("20%", "46%", "25%", "15%", "供应商"); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("35%", "10%", "23%", "15%", "PO/SA"); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT(
    "33%",
    "27%",
    "20%",
    "15%",
    formData.poSa + " / " + formData.poSaItem
  ); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("54%", "10%", "23%", "15%", "批次"); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("54%", "27%", "25%", "15%", formData.batch); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("69%", "10%", "23%", "15%", "流水号"); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("69%", "27%", "25%", "15%", formData.serial); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("84%", "10%", "23%", "15%", "数量"); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_TEXT("84%", "27%", "25%", "15%", formData.number); //边框设置：上、左、宽、高

  LODOP.SET_PRINT_STYLE("FontSize", 7);
  LODOP.ADD_PRINT_TEXT("3%", "61%", "33%", "15%", formData.materialName); //边框设置：上、左、宽、高 ---物料描述
  LODOP.ADD_PRINT_TEXT("17%", "61%", "31%", "15%", formData.partnerName); //边框设置：上、左、宽、高 ---供应商

  LODOP.SET_PRINT_STYLE("FontSize", 8);
  LODOP.ADD_PRINT_TEXT("93%", "12%", "100%", "6%", pCode.value); //边框设置：上、左、宽、高
  LODOP.ADD_PRINT_BARCODE("35%", "55%", "25%", "25%", "QRCode", pCode.value);
  // LODOP.ADD_PRINT_HTM(
  //   10,
  //   10,
  //   300,
  //   300,
  //   document.getElementById(`printId`)?.innerHTML
  // );
  LODOP.NEWPAGE(); //另起一页
  LODOP.PREVIEW();
  //LODOP.PRINT(); // 打印

  // setTimeout(() => {
  //   setSerial();
  //   getBarCode();
  // }, 1000);
}
</script>
<style scoped>
table {
  border-right: 1px solid #0000001f;
  border-bottom: 1px solid #0000001f;
  text-align: center;
}

table td {
  height: 70px;
  border-left: 1px solid #0000001f;
  border-top: 1px solid #0000001f;
  width: 25%;
}
</style>
